<template>
  <div>
    <h4 style="margin:10px 0">
      <el-row>
        <el-col :span="5">
          <span v-if="editVal">修改医院账号</span>
          <span v-else>添加医院账号</span>
          <el-button class="addBtn" @click="resetForm('ruleForm2')">返回</el-button>
        </el-col>
      </el-row>
    </h4>
    <div style="width:80%;margin:0 auto">
      <el-form :model="ruleForm2"  :rules="rules2" ref="ruleForm2" label-width="80px" class="demo-ruleForm">
        <el-form-item label="医院名称" prop="hospital_name">
          <el-input v-model.number="ruleForm2.hospital_name"  ></el-input>
        </el-form-item>

        <el-form-item label="账号" prop="account_name">
          <el-input v-model.number="ruleForm2.account_name"></el-input>
        </el-form-item>
        
        <div v-if="editVal">
          <el-form-item label="密码">
            <el-input type="password" v-model="ruleForm2.pass"  ></el-input>
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input type="password" v-model="ruleForm2.checkPass" ></el-input>
          </el-form-item>
        </div>

        <div v-else>
          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="ruleForm2.pass"  ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="ruleForm2.checkPass" ></el-input>
          </el-form-item>
        </div>

        <el-form-item label="是否启用" prop="hospital_status">
           <el-select v-model="ruleForm2.hospital_status" placeholder="请选择">
              <el-option v-for="(item,index) in options" :key="index" :value="item.value" :label="item.label"></el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input  v-model="ruleForm2.tel" ></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="business_time">
          <el-input v-model="ruleForm2.business_time"></el-input>
        </el-form-item>
         <el-form-item label="区域" prop="parenodress">
          <el-select v-model="ruleForm2.province" @change="changeCity" filterable placeholder="请选择省份">
            <el-option v-for="item in ruleForm2.options1" :key="item.id" :label="item.areaname" :value="item.id" > </el-option>
          </el-select>
          <el-select v-model="ruleForm2.city" @change="changeArea" filterable placeholder="请选择城市">
            <el-option v-for="item in ruleForm2.options2" :key="item.id" :label="item.areaname" :value="item.id"> </el-option>
          </el-select>
          <el-select v-model="ruleForm2.area" @change="changeVal" filterable placeholder="请选择区">
            <el-option v-for="item in ruleForm2.options3" :key="item.id" :label="item.areaname" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体地址" prop="position">
          <el-input v-model="ruleForm2.position"  @blur="getLng" placeholder="请填写详细地址"></el-input>
          <div>
            <span>{{address}}</span>
            <span v-if="okLng== 1" style="margin-left:20px;color:#67c23a">经纬度获取成功</span>
            <span v-else-if="okLng== 2" style="margin-left:20px;color:red">无法获取该得知的经纬度获取</span>
            <span v-else></span>
          </div>
        </el-form-item>
        <el-form-item label="Logo" prop="odress" style="width:100%">
          <div>
            <el-upload 
              class="avatar-uploaderInfo"
              :action="action"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleOkLogo"
              :data="postData">
              <img v-if="ruleForm2.logo_url" :src="ruleForm2.logo_url" class="avatarInfo">
              <i v-else class="el-icon-plus avatar-uploader-iconInfo"></i>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="图片" prop="odress">
          <div>
             <el-row>
              <el-col :span="24">
                <ul class="el-upload-list el-upload-list--picture-card">
                  <li style="float:left" :tabindex="index" class="el-upload-list__item is-success" v-for="(item,index) in fileList3" :key="index">
                    <img :src="item" alt="" class="el-upload-list__item-thumbnail">
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="shouimg(item)"><i class="el-icon-zoom-in"></i></span>
                      <span class="el-upload-list__item-delete" @click="deletImg(index)"><i class="el-icon-delete"></i></span>
                    </span>
                  </li>
                </ul>
                <el-upload  style="float:left"
                  :action="action"
                  list-type="picture-card"
                  :show-file-list="false"
                  :on-success="handleOkList"
                  :before-upload="beforeAvatarUpload"
                  :data="postData">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="简介" prop="odress">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="ruleForm2.introduction"></el-input>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-row>
          <el-col :span="12">
            <el-button type="primary" v-if="editVal" @click="editFun">保 存</el-button>
            <el-button type="primary" v-else @click="submitForm('ruleForm2')">提 交</el-button>
          </el-col>
          <el-col :span="12">
            <el-button @click="resetForm('ruleForm2')">取 消</el-button>
          </el-col>
        </el-row>
      </div>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="Imhospital_nameUrl" alt="">
      </el-dialog>
    </div>
    <div v-show="showMap" id="XSDFXPage" class="XSDFXPage"></div>
  </div>
</template>

<script>
import Http from '@/Http/Http'
import qnUrl from '@/Http/qiniuUrl'
import crypto from 'crypto'
export default {
  props:['editVal'],
  
  created(){
    this.getToken();
    if ( this.editVal) {
      this.ruleForm2.pass = '83749211';
      this.ruleForm2.checkPass = 'fdswerew';
      this.ruleForm2.hospital_name = this.editVal.name;
      this.ruleForm2.account_name = this.editVal.account_name;
      this.ruleForm2.hospital_name = this.editVal.name;
      this.ruleForm2.hospital_status = this.editVal.status;
      this.ruleForm2.tel = this.editVal.tel;
      this.ruleForm2.business_time = this.editVal.business_time;
      this.ruleForm2.introduction = this.editVal.introduction;
      this.ruleForm2.logo_url = this.editVal.logo_url;
      this.fileList3 = this.editVal.images;
      this.ruleForm2.position = this.editVal.position;
      
    }
  },
   mounted() {
           
      // 百度地图API功能
      // 创建Map实例
      this.map = new BMap.Map("XSDFXPage",{enableMapClick:true});
      this.map.centerAndZoom("深圳",12);           
      this.map.enableScrollWheelZoom();    //启用滚轮放大缩小，默认禁用
      this.map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用

      this.map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
      this.map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件
      this.map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT }));   //右下角，打开

      this.localSearch = new BMap.LocalSearch(this.map);
      this.localSearch.enableAutoViewport(); //允许自动调节窗体大小
      
    //this.map.addEventListener("click", this.showInfo);
  },
  data() {
    var account_name = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'));
      } else {
        callback();
      }
    };
    var checkhospital_name = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('名称不能为空'));
      } else {
        callback();
      }
    };
    var Pass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm2.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var tel = (rule, value, callback) => {
     
      if(value == ''){
        return callback(new Error('输入电话号码'));
      } else {
        callback();
      }
    };

    return {
      action:qnUrl,//七牛的上传地址
      postData:{
        token:'',
      },
      showMap:false, //显示地图
      map:'',
      editSta:true,
      Imhospital_nameUrl:'', //放大图片地址
      dialogVisible:false, //放大图片状态
      tokenimgUrl:'',
      address:'',
      okLng:0,
      mapdata:{ //获取经纬度
        lat:'',
        lng:''
      },
      fileList3:[],
      options:[
        {label:'上线',value:1},
        {label:'下线',value:2}
      ],
      ruleForm2: {
        options1:[],
        options2:[],
        options3:[],
        province:'',//省
        city:'',//市
        area:'',//区
        pass: '',
        checkPass:'',
        tel:'',
        account_name:'',
        hospital_status: 2, //是否启用
        hospital_name: '',
        logo_url:'', //logo地址
        business_time:'', //营业时间
        position:'',//具体地址
        introduction:'' //简介
      },
      rules2: {
        account_name: [
          { validator: account_name, trigger: 'blur' }
        ],
        pass: [
          { validator: Pass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        hospital_name: [
          { validator: checkhospital_name, trigger: 'blur' }
        ],
        tel: [
          { validator: tel, trigger: 'blur' }
        ]
      }
    };
  },
  
  methods: {
    getToken() {
      Http.QiniuToken({})
        .then( res => {
          this.postData.token = res.data.data.uptoken;
          this.tokenimgUrl = res.data.data.domain
        })
        .catch( error => {
          this.$router.push('/')
          
        })
      Http.getAreaList(0)
        .then( res => {         
          this.ruleForm2.options1 = res.data.data;
          
           if ( this.editVal) {
             this.ruleForm2.province = this.editVal.province_id;

             Http.getAreaList(this.editVal.province_id)
            .then( res => {
              this.ruleForm2.options2 = res.data.data;
              this.ruleForm2.city = this.editVal.city_id;
              
            })
            Http.getAreaList(this.editVal.city_id)
            .then( res => {
              
              this.ruleForm2.options3 = res.data.data;
               this.ruleForm2.area = this.editVal.area_id;
            })
           }
        })
    },
    
    changeCity(val){
      Http.getAreaList(val)
        .then( res => {
          this.ruleForm2.options2 = res.data.data;
          this.ruleForm2.options3 = '';
          this.ruleForm2.area = '';
          this.ruleForm2.city = '';
          
        })
    },
    changeArea(val){
      Http.getAreaList(val)
        .then( res => {
          this.ruleForm2.area = '';
          this.ruleForm2.options3 = res.data.data;
           
        })
    },
    changeVal(val){

    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (isJPG || isPNG) {
        return true;
      } else {
          this.$message.error('上传图片格式不正确!');
        return false;
      }
    },
    handleOkLogo(responed) {
      this.ruleForm2.logo_url = `http://${this.tokenimgUrl}/${responed.key}`;
      
    },


    // 图片列表 方法  -------------------------------------------------------|||||
    
    handleOkList(responed,fill,filist) {
      this.fileList3.push(`http://${this.tokenimgUrl}/${responed.key}`) ;
      
    },
    shouimg(val) {
      this.dialogVisible = true;
      this.Imhospital_nameUrl = val;
    },
    deletImg(index) {
      this.fileList3.splice(index,1)
    },

     // 图片列表 方法  -------------------------------------------------------|||||

     handleItemChange(val) {

     },

    submitForm(formName) {
      
      this.$refs[formName].validate((valid) => {
        if (!valid) { 
          this.$message.error('信息未填完整')
          return 
        } 
        
        const md5 = crypto.createHash("md5");
          md5.update(this.ruleForm2.pass);
        const psw = md5.digest('hex')
        const obj = {
          "hospital_name":this.ruleForm2.hospital_name,
          "account_name":this.ruleForm2.account_name,
          "password":psw,
          "hospital_status":this.ruleForm2.hospital_status, //启用
          "province_id":this.ruleForm2.province,
          "city_id":this.ruleForm2.city,
          "area_id":this.ruleForm2.area,
          "hospitalInfo":{
            "logo_url":this.ruleForm2.logo_url,
            "business_time":this.ruleForm2.business_time,
            "position":this.ruleForm2.position,
            "lng":this.mapdata.lng,
            "lat":this.mapdata.lat,
            "tel":this.ruleForm2.tel,
            "introduction":this.ruleForm2.introduction,
            "images":this.fileList3
          }
        }
        this.addAdminFun(obj)
      });
    },
    editFun() {
      let psw='';
      if(this.ruleForm2.pass != '83749211' || this.ruleForm2.checkPass != 'fdswerew'){
        if(this.ruleForm2.checkPass == this.ruleForm2.pass){
          const md5 = crypto.createHash("md5");
            md5.update(this.ruleForm2.pass);
           psw = md5.digest('hex')
        } else {
          this.$message.error('两次密码不一致')
          return
        }
      };
      
      const obj = {
        "status":this.ruleForm2.hospital_status, //启用
        "province_id":this.ruleForm2.province,
        "hospital_id":this.editVal.hospital_id,
        "city_id":this.ruleForm2.city,
        "area_id":this.ruleForm2.area,
        "logo_url":this.ruleForm2.logo_url,
        "business_time":this.ruleForm2.business_time,
        "position":this.ruleForm2.position,
        "lng":this.mapdata.lng,
        "lat":this.mapdata.lat,
        "tel":this.ruleForm2.tel,
        "introduction":this.ruleForm2.introduction,
        "images":this.fileList3
      };
      if(psw){
        obj.password = psw;
      };
      this.editAdminFun(obj)
    },
    addAdminFun(obj){
      Http.addHospitAdmin(obj)
      .then( res => {
        if( res.data.code == 200 ){
          this.$message.success('账号添加成功')
            this.$emit('colseFun')
        } else if(res.data.code == -1003) {
            this.$message.error(`token过期，请重新登录`)
            this.$router.push('/')
        } else {
          this.$message.error('账号添加失败')
        }
      })
    },
    editAdminFun(obj){
       Http.editHospitAdmin(obj)
      .then( res => {
        if( res.data.code == 200 ){
          this.$message.success('账号修改成功')
            this.$emit('colseFun')
        } else if(res.data.code == -1003) {
            this.$message.error(`token过期，请重新登录`)
            this.$router.push('/')
        } else {
          this.$message.error('账号修改失败')
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$emit('colseFun')
    },
    getLng() {
      let a,b,c;
      this.ruleForm2.options1.forEach(item => {
        if(item.id == this.ruleForm2.province){
          a = item.areaname
        }
      })
      if(this.ruleForm2.options2){
         this.ruleForm2.options2.forEach(item => {
          if(item.id == this.ruleForm2.city){
            b = item.areaname
          }
        })
      }
      if(this.ruleForm2.options3){
        this.ruleForm2.options3.forEach(item => {
          if(item.id == this.ruleForm2.area){
            c = item.areaname
          }
        })
      }
      
      if(!a || !b || !c){
        this.$message.error('请选择省，市，区');
        return
      }
      this.address = `${a}${b}${c}${this.ruleForm2.position}`;
      this.searchByStationName()

    },
    searchByStationName() {
       this.okLng = 0;        
      this.map.clearOverlays();//清空原来的标注
      var keyword = this.address;
      const _this = this;
      this.localSearch.setSearchCompleteCallback(function (searchResult) {
          
          var poi = searchResult.getPoi(0);
          
          if(!poi){
            _this.okLng = 2;
            return
          }
          _this.vala = poi.point.lng + "," + poi.point.lat;
          _this.mapdata.lng = poi.point.lng,
          _this.mapdata.lat = poi.point.lat,
          if(_this.mapdata.lng){
            _this.okLng = 1;
          } else {
            _this.okLng = 2;
          }
          _this.map.centerAndZoom(poi.point, 13);
          var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat));  // 创建标注，为要查询的地方对应的经纬度
          _this.map.addOverlay(marker);
          var content = _this.aderss + "<br/><br/>经度：" + poi.point.lng + "<br/>纬度：" + poi.point.lat;
          var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + content + "</p>");
          marker.addEventListener("click", function () { this.openInfoWindow(infoWindow); });
          // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
      });
      _this.localSearch.search(keyword);
    },
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
    display: none;
}
.avatar-uploaderInfo .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploaderInfo .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-iconInfo {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatarInfo {
  width: 178px;
  height: 178px;
  display: block;
}
 .XSDFXPage{
      width: 400px;
      height: 500px;
      overflow: hidden;
      margin: 0;
      font-family: "微软雅黑";
  }
</style>
